<template>
  <div class="user">
        <!--头部面包屑导航-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!--卡片视图-->
        <el-card class="box-card">
            <div class="header">
                <el-input placeholder="请输入搜索内容" class="ipt" clearable v-model.trim="queryInfo.query"
                @clear="getuserlists">
                    <el-button slot="append" icon="el-icon-search" @click="getuserlists"></el-button>
                </el-input>
                <el-button type="primary" @click="adduser"> 添加用户 </el-button>
            </div>
            <!--表格区域 -->
            <el-table
                :data="userlists"
                border
                stripe
                 style="width: 100%">
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column prop="username" label="姓名"></el-table-column>
                <el-table-column prop="email" label="邮箱"></el-table-column>
                <el-table-column prop="mobile" label="电话"></el-table-column>
                <el-table-column prop="role_name" label="角色"></el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">
                        <el-switch
                            @change="switchchange(scope.row)"
                            v-model="scope.row.mg_state"
                            active-color="#13ce66"
                            inactive-color="#ff4949">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column  label="操作">
                    <template slot-scope="scope">
                        <el-tooltip class="item" :enterable="false" effect="dark" content="修改" placement="top">
                            <el-button type="primary" icon="el-icon-edit" circle @click="edituser(scope.row)"></el-button>
                        </el-tooltip>
                        <el-tooltip class="item" :enterable="false" effect="dark" content="删除"  placement="top">
                            <el-button type="danger" icon="el-icon-delete" circle @click="canleuser(scope.row)"></el-button>
                        </el-tooltip>
                        <el-tooltip class="item" :enterable="false" effect="dark" content="分配角色" placement="top">
                            <el-button type="info" icon="el-icon-setting" circle @click="setrole(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 做分页功能 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[1, 2, 3, 4, 5]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="this.total">
           </el-pagination>
        </el-card>
        <!--点击添加用户的弹出框-->
        <el-dialog
            title="添加用户"
            :visible.sync="adduserdialogVisible"
            width="30%"
            :show-close="false"
            :before-close="handleClose">
            <el-form :model="adduserruleForm" :rules="adduserrules" ref="adduserruleForm" label-width="70px" >
                <el-form-item label="用户名" prop="name">
                    <el-input v-model.trim="adduserruleForm.name"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model.trim="adduserruleForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model.trim="adduserruleForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model.trim="adduserruleForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="canleuser('adduserruleForm')">取 消</el-button>
                <el-button type="primary" @click="sureuser('adduserruleForm')">确 定</el-button>
            </span>
        </el-dialog>
        <!--点击修改按钮的弹出框-->
        <el-dialog
            title="修改用户"
            :visible.sync="edituserdialogVisible"
            width="30%"
            :show-close="false"
            @close="editclose"
            :before-close="handleClose">
            <el-form :model="edituserruleForm" :rules="edituserrules" ref="edituserruleForm" label-width="70px" >
                <el-form-item label="用户名" prop="username">
                    <el-input v-model.trim="edituserruleForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model.trim="edituserruleForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model.trim="edituserruleForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editcanleuser('edituserruleForm')">取 消</el-button>
                <el-button type="primary" @click="editsureuser">确 定</el-button>
            </span>
        </el-dialog>
        <!--分配角色的弹出框-->
        <el-dialog
            title="提示"
            :visible.sync="setroledialogVisible"
            width="30%"
            @close="selectroleid=''">
            <div>
                <p>当前的用户：{{userinfo.username}}</p>
                <p>当前的角色：{{userinfo.role_name}}</p>
                <p>分配新的角色： 
                    <el-select v-model="selectroleid" placeholder="请选择">
                        <el-option
                        v-for="item in roleslist"
                        :key="item.id"
                        :label="item.roleName"
                        :value="item.id">
                        </el-option>
                    </el-select>
                </p>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setroledialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="setrolesure">确 定</el-button>
            </span>
        </el-dialog>
  </div>
</template>

<script>
export default {
    data(){
        //自定义邮箱的校验规则
        var validatoremail = (rule,value,callback)=>{
            const regmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
            if(regmail.test(value))
            return callback()
            callback(new Error("请输入合法的邮箱"))
        }
        //自定义手机号的校验规则
        var validatormobil = (rule,value,callback)=>{
            const regmobil = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
            if(regmobil.test(value))
            return callback()
            callback(new Error("请输入合法的号码"))
        }
        return{
            userlists:[],
            roleslist:[],//角色列表数据(下拉菜单使用)
            selectroleid:"",//角色列表数据(下拉菜单选中的id)
            total:4,//用户列表数据总条数
            queryInfo:{
                query:"",
                pagenum:1,
                pagesize:2
            },//获取用户列表数据的参数对象
            adduserdialogVisible:false,//添加用户的弹出框
            edituserdialogVisible:false,//修改用户的弹出框
            setroledialogVisible:false,//分配角色的对话框
            adduserruleForm:{
                name:'',
                password:'',
                email:"",
                mobile:""
            },
            edituserruleForm:{
                username:'',
                password:'',
                email:"",
                mobile:""
            },
            adduserrules: {
                name: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
                ],
                email: [
                     {required: true, message: '请输入手机号', trigger: 'blur' },
                     { validator: validatoremail,  trigger: 'blur' },
                ],
                mobile: [
                    {required: true, message: '请输入手机号' ,trigger: 'blur' },
                    { validator: validatormobil, trigger: 'blur'  },
                ]
            },
            edituserrules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
                ],
                email: [
                     {required: true, message: '请输入手机号', trigger: 'blur' },
                     { validator: validatoremail,  trigger: 'blur' },
                ],
                mobile: [
                    {required: true, message: '请输入手机号' ,trigger: 'blur' },
                    { validator: validatormobil, trigger: 'blur'  },
                ]
            },
            userinfo:{} //需要被分配角色的用户信息
            
        }
    },
    created(){
        // 获取用户列表数据
        this.getuserlists()
    },
    methods:{
        // 获取用户列表数据
        async getuserlists(){
           const {data:res} = await this.$http.get('users',{params:this.queryInfo})
           if(res.meta.status!=200) return this.$message.error("获取用户列表数据失败")
           this.userlists = res.data.users
           this.total = res.data.total
           console.log(this.userlists)
       },
       //修改每页显示条数
       handleSizeChange(e){
           console.log(e)
           this.queryInfo.pagesize = e
           this.getuserlists()
       },
       //修改去第几页
       handleCurrentChange(e){
           this.queryInfo.pagenum = e
           this.getuserlists()
       },
       //修改状态栏数据
       async switchchange(e){
           const {data:res}= await this.$http.put(`users/${e.id}/state/${e.mg_state}`)
           if(res.meta.status!=200){
               e.status = !e.status
               return this.$message.error("状态修改失败")
           }
           return this.$message.success("状态修改成功")
       },
       //添加用户
       adduser(){
           this.adduserdialogVisible = true
       },
       handleClose(){

       },
       //点击弹出框中中取消的处理函数
       canleuser(formName){
            this.adduserdialogVisible = false
            this.$refs[formName].resetFields(); 
       },
       //点击了弹出框中确定的处理函数
       sureuser(formName){
        //    完成表单的预验证
            this.$refs[formName].validate(async valid=>{
                if(!valid)
                return 
                //预校验通过发起请求添加用户
                const {data:res} = await this.$http.post('users',{
                    username:this.adduserruleForm.name,
                    password:this.adduserruleForm.password,
                    email:this.adduserruleForm.email,
                    mobile:this.adduserruleForm.mobile
                }) 
                console.log(res)
                if(res.meta.status!=201) return this.$message.error("添加用户失败")
                else{
                    this.adduserdialogVisible = false
                    this.$refs[formName].resetFields(); 
                    this.getuserlists()
                    return this.$message.success("添加用户成功")
                }
            })
       },
       //修改用户信息
       edituser(e){
           this.edituserdialogVisible =true
           this.edituserruleForm = e
       },
       //点击了修改用户弹出框中取消的函数处理
       editcanleuser(formName){
           this.edituserdialogVisible = false
       },
       //点击了修改用户弹出框中确定的函数处理
       editsureuser(){
           console.log()
           this.edituserdialogVisible =false
            //提交修改后的预验证
            this.$refs.edituserruleForm.validate(async valid=>{
                if(!valid) return 
                //预校验通过
                const {data:res} = await this.$http.put(`users/${this.edituserruleForm.id}`,{
                   email:this.edituserruleForm.email,
                   mobile:this.edituserruleForm.mobile
               })
               if(res.meta.status!=200) return this.$message.error("修改用户信息失败")
               console.log(res)
               this.getuserlists()
               return this.$message.success("修改用户信息成功")
            })
       },
       //修改框修改后的关闭处理函数
       editclose(){
           this.$refs.edituserruleForm.resetFields()
       },
       // 删除用户
       async canleuser(user){
           console.log(user.id)
                const res= await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                }).catch(err=>err)
                console.log(res)
                if(res!=="confirm") return this.$message.info("您取消了本次删除")
                else{
                    //发起请求删除用户
                    const {data:resinfo} =  await this.$http.delete('users/'+user.id)
                    if(resinfo.meta.status!=200) return this.$message.error("删除用户失败")
                    this.getuserlists()
                    return this.$message.success("删除成功")
                }       
        },
        // 分配角色
        async setrole(row){
            this.userinfo= row
            // 展示对话框之前获得所以的角色列表
            const {data:res}= await this.$http.get('roles')
            if(res.meta.status!=200) return this.$message.error("获取角色列表数据失败")
            this.roleslist= res.data
            this.setroledialogVisible = true
        },
        //点击了分配角色弹出框确认按钮的处理情况
        async setrolesure(){
            if(!this.selectroleid) return ths.$message.error("请选择要分配的角色")
            //发起请求保存用户选择的角色
            const {data:res} = await this.$http.put(`users/${this.userinfo.id}/role`,{
                rid:this.selectroleid
            })
            if(res.meta.status!=200) return this.$message.error("分配角色失败")
            this.getuserlists()
            this.setroledialogVisible =false
            return this.$message.success("分配角色成功")
        }

    }
}
</script>

<style scoped>
.header{
    display: flex;
    flex-wrap: nowrap;
    margin-bottom: 10px;
}
.header .ipt{
    width: 20%;
    margin-right: 20px;
}
</style>